package com.ltmonitor.web.controller.websocket;

import com.ltmonitor.util.DateUtil;
import com.ltmonitor.vo.JT808MessageVo;
import com.ltmonitor.web.util.OnlineUser;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.*;
import java.util.Map.Entry;

public class JT808MessageWebSocketHandler extends TextWebSocketHandler {
	private static Map<String, WebSocketClient> socketClients = new HashMap<String, WebSocketClient>();

	private static Logger logger = Logger.getLogger(JT808MessageWebSocketHandler.class);

	@Override
	public void handleTextMessage(WebSocketSession session, TextMessage message) {
		WebSocketClient sendClient = socketClients.get(session.getId());
		String nickName = sendClient.getNickName();
		String clientIp = sendClient.getClientIp();

		//System.out.println("handleTextMessage: " + session.getId() + "-" + nickName + "-" + message.getPayload());

	}

	/**
	 * 给所有在线用户发送消息
	 * 
	 * @param message
	 * @throws IOException
	 */
	public void broadcast(final TextMessage message) throws IOException {
		Iterator<Entry<String, WebSocketClient>> it = socketClients.entrySet().iterator();

		// 多线程群发
		while (it.hasNext()) {

			final Entry<String, WebSocketClient> entry = it.next();

			if (entry.getValue().getSocketSession().isOpen()) {
				// entry.getValue().sendMessage(message);
				new Thread(new Runnable() {

					public void run() {
						try {
							if (entry.getValue().getSocketSession().isOpen()) {
								entry.getValue().getSocketSession().sendMessage(message);
							}
						} catch (IOException e) {
							e.printStackTrace();
						}
					}

				}).start();
			}

		}
	}

	/**
	 * 给所有的在线用户，根据权限，推送报警信息
	 * @param messageList
	 * @throws IOException
	 */
	public void broadcast(List<JT808MessageVo> messageList) throws IOException {
		Iterator<Entry<String, WebSocketClient>> it = socketClients.entrySet().iterator();

		// 多线程群发
		while (it.hasNext()) {

			final Entry<String, WebSocketClient> entry = it.next();

			WebSocketClient c = entry.getValue();
			final WebSocketSession session = c.getSocketSession();
			if (session.isOpen()) {
				Date start2 = new Date();
				// entry.getValue().sendMessage(message);
				OnlineUser user = (OnlineUser) session.getAttributes().get("onlineUser");

				JSONArray list = new JSONArray();
				for (JT808MessageVo message : messageList) {

					if (this.isAuthorized(user, message)) {
						try {
							JSONObject j = JSONObject.fromObject(message);
							list.add(message);
							
						} catch (Exception e) {
							logger.error(e.getMessage(), e);
						}
					}
				}
				
				if(list.size() > 0)
				{
					TextMessage t = new TextMessage(list.toString());
					// logger.error(t.toString());
					session.sendMessage(t);
					Date endDate2 = new Date();
					double min2 = DateUtil.getSeconds(start2, endDate2);
					if(min2 > 1)
					logger.error("推送报警耗时:" + min2 + "秒");
				}
			}

		}

	}

	/**
	 * 给所有在线用户发送消息
	 * 
	 * @param message
	 * @throws IOException
	 */
	public void broadcast(final JT808MessageVo message) throws IOException {
		Iterator<Entry<String, WebSocketClient>> it = socketClients.entrySet().iterator();

		// 多线程群发
		while (it.hasNext()) {

			final Entry<String, WebSocketClient> entry = it.next();

			WebSocketClient c = entry.getValue();
			final WebSocketSession session = c.getSocketSession();
			if (session.isOpen()) {
				// entry.getValue().sendMessage(message);
				OnlineUser user = (OnlineUser) session.getAttributes().get("onlineUser");
				if (this.isAuthorized(user, message)) {
					try {
						if (session.isOpen()) {
							JSONObject j = JSONObject.fromObject(message);
							TextMessage t = new TextMessage(j.toString());
							// logger.error(t.toString());
							session.sendMessage(t);
						}
					} catch (Exception e) {
						logger.error(e.getMessage(), e);
					}
				}
			}

		}
	}

	/**
	 * 判断该消息是否有权限推送给某一个用户
	 * 
	 * @param user
	 * @param message
	 * @return
	 */
	private boolean isAuthorized(OnlineUser user, JT808MessageVo message) {
		if (user == null)
			return false;

		return true;
	}

	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		String userName = (String) session.getAttributes().get("userName");
		String sessionID = session.getId();
		String nickName = "";
		String path = URLDecoder.decode(session.getUri().getPath(), "UTF-8");
		String[] paths = path.split("\\/");
		for (int i = 0; i < paths.length; ++i) {
			if (paths[i].equalsIgnoreCase("nickname")) {
				if (i < paths.length - 1)
					nickName = paths[i + 1];
				break;
			}
		}

		//System.out.println("afterConnectionEstablished: " + sessionID + "-" + nickName + "," + userName);

		String clientIp = session.getRemoteAddress().getAddress().getHostAddress();
		WebSocketClient client = new WebSocketClient();
		client.setClientIp(clientIp);
		client.setNickName(nickName);
		client.setSocketSession(session);

		socketClients.put(sessionID, client);
	}

	@Override
	public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
		System.out.println("handleTransportError");
	}

	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
		//System.out.println("afterConnectionClosed");

		String sessionID = session.getId();
		socketClients.remove(sessionID);
	}

	@Override
	public boolean supportsPartialMessages() {
		// TODO Auto-generated method stub
		return false;
	}

}
